package com.qububu.play.common.control;

import static com.qububu.utils.ParamConverter.assertNotEmpty;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qububu.common.user.dto.UserInfoDto;
import com.qububu.play.common.dto.ArticleAuthor;
import com.qububu.play.common.dto.ArticleDetailMsgDto;
import com.qububu.play.common.dto.ArticleDetailMsgDto.ArticleTypeMsg;
import com.qububu.play.common.dto.ArticleInfoDto;
import com.qububu.play.common.dto.ArticleInfoDto.ArticleType;
import com.qububu.play.common.service.PlayArticleService;
import com.qububu.utils.DateUtil;
import com.qububu.utils.ParamConverter;
import com.qububu.utils.SystemConstants;
import com.qububu.utils.SystemUtil;


@Controller
@RequestMapping("/play/article")
public class PlayArticleControl {

	@Resource
	private PlayArticleService playArticleService;
	
	// 显示帖子的路径
	@RequestMapping("/showPosts")
	public String showPosts(HttpServletRequest req) {
		
		int articleId = ParamConverter.convertToInteger(SystemUtil.decrypt(assertNotEmpty(req.getParameter("a"))));
		
		Map<String, Object> articleDetailMap = playArticleService.getFirstArticleAndSomeCommentByArticleId(articleId);
		
		ArticleDetailMsgDto articleMsgInfo = (ArticleDetailMsgDto) articleDetailMap.get("articleMsgInfo");
		List<ArticleDetailMsgDto> sonMsgList = (List<ArticleDetailMsgDto>) articleDetailMap.get("sonMsgList");
		req.setAttribute("article", articleMsgInfo);
		req.setAttribute("sonMsgList", sonMsgList);
		
		return "showPost";
	}
	
	// 写帖子的路径
	@RequestMapping("/writePosts")
	public String writePosts() {
		
		return "writePosts";
	}
	
	/**
	 * 加载数据及获得缓存ID
	 * */
	@RequestMapping("/getPeoplesArticles")
	@ResponseBody
	public Map<String, Object> queryArticleListByArticleIdOrArticleType(HttpServletRequest request, HttpServletResponse response){
		
		String articleType = ParamConverter.assertNotEmpty(request.getParameter("at")); // 获取文章类型
		String actionId = ParamConverter.assertNotEmpty(request.getParameter("ai")); // 获取文章ID
		int type = ArticleType.getArticleType(articleType).toIntValue();
		
		int pageNum = ParamConverter.convertToInteger(assertNotEmpty(request.getParameter("pageNum")));
		if (pageNum < 0 ) {
			pageNum = 0;
		}
		
		List<ArticleInfoDto> articleList = playArticleService.getArticleListByActionId(type, actionId, pageNum);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("result", SystemConstants.AJAX_SUCCESS);
		resultMap.put("articleList", articleList);

		return resultMap;
	}
	
	/**
	 * @功能 根据type dine分页
	 */
	@RequestMapping("/getArticles")
	@ResponseBody
	public Map<String, Object> getArticles(HttpServletRequest req) {
		
		String articleType = ParamConverter.assertNotEmpty(req.getParameter("articleType"));
		int type = ArticleType.getArticleType(articleType).toIntValue();
		int pageNum = ParamConverter.convertToInteger(assertNotEmpty(req.getParameter("pageNum")));
		if (pageNum < 0 ) {
			pageNum = 0;
		}
		List<ArticleInfoDto> articleList = playArticleService.getArticleList(type, pageNum);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("result", SystemConstants.AJAX_SUCCESS);
		resultMap.put("articleList", articleList);
		
		return resultMap;
	}
	
	
	/**
	 * @功能 查询一篇文章及其一级评论，并且实现分页
	 */
	@RequestMapping("/getArticleDetails")
	@ResponseBody
	public Map<String, Object> queryArticleInfoDetail(HttpServletRequest request, HttpServletResponse response){

		int articleId = ParamConverter.convertToInteger(SystemUtil.decrypt(assertNotEmpty(request.getParameter("articleId"))));
		int pageNum = ParamConverter.convertToInteger(assertNotEmpty(request.getParameter("pageNum")));
		
		if (pageNum < 0 ) {
			pageNum = 0;
		}
		
		List<ArticleDetailMsgDto> detailMessageList = playArticleService.getArticleDetailsByMessageId(articleId, pageNum);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("result", SystemConstants.AJAX_SUCCESS);
		resultMap.put("details", detailMessageList);
		
		return resultMap;
	}
	
	
	/**
	 * @功能 由一级评论的msgId查出对一级评论的回复(二级评论)
	 */
	@RequestMapping("/getArticleDetailReplys")
	@ResponseBody
	public Map<String, Object> queryArticleDetailReplys(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> articleReplyMap = new HashMap<String, Object>();
		
		String msgId = SystemUtil.decrypt(assertNotEmpty(request.getParameter("msgId")));
		int msgIdInt = ParamConverter.convertToInteger(msgId);

		List<ArticleDetailMsgDto> articleReplyList = playArticleService.getArticleInfoReplyByMsgId(msgIdInt);
		
		articleReplyMap.put("result", SystemConstants.AJAX_SUCCESS);
		articleReplyMap.put("articleReplyList", articleReplyList);
		
		return articleReplyMap;			
	}
	
	
	/**
	 * @功能 添加文章部分和全部内容
	 * @author LH
	 * */
	@RequestMapping("/addArticle")
	public String addArticle(HttpServletRequest request, HttpServletResponse response) {
		if (request.getSession().getAttribute(SystemConstants.LOGINUSER_SESSION_NAME) != null) {
			String articleTitle = SystemUtil.convertSpecialMark(assertNotEmpty(request.getParameter("article_title")));
			
			int titleLength = 35;
			String articleTitleSub = articleTitle.length() >= titleLength ? articleTitle.substring(0, titleLength) : articleTitle;
			
			String articleContent = SystemUtil.removeAllScriptFromHtml(assertNotEmpty(request.getParameter("article_text")));
			String articleType = assertNotEmpty(request.getParameter("article_type"));
			
			UserInfoDto dto = (UserInfoDto) request.getSession().getAttribute(SystemConstants.LOGINUSER_SESSION_NAME);
			String userId = dto.getUserId();
			
			String articleCreateIp = assertNotEmpty(SystemUtil.getRequestIp(request));
			String contextPath = request.getContextPath();
			
			ArticleInfoDto articleInfo = getSummaryArticleMessage(articleTitleSub, articleContent, articleType, userId, articleCreateIp, contextPath);
			ArticleDetailMsgDto articleMsg = getArticleInfoMsg(null, null, articleTitleSub, articleContent, articleType, userId, articleCreateIp, contextPath);
			
			long articleId = playArticleService.doAddArticle(articleInfo, articleMsg);
			
			return "redirect:/play/article/showPosts?a="+SystemUtil.encrypt(String.valueOf(articleId));
		}
		return "redirect:/play/article/writePosts";
	}
	
	private ArticleInfoDto getSummaryArticleMessage(String title, String content, String type, String userId, String createIp, String contextPath) {
		String artSummaryPicUrl = SystemUtil.getSummaryPicUrl(content, contextPath);
		
		int summaryContentLength = artSummaryPicUrl == null ? 120 : 40;
		
		String articleSummaryText = SystemUtil.getSummaryText(SystemUtil.removeAllTagFromHtml(content), summaryContentLength);
		int articleCreateDttm = DateUtil.convertCurrentDTTMtoInt();
		// SystemUtil.convertSpecialMark(content)
		return createArticleInfoDto(SystemUtil.getUUIDString(), title, articleSummaryText, artSummaryPicUrl, articleCreateDttm, createIp, type, userId);
	}
	
	private ArticleDetailMsgDto getArticleInfoMsg(String messageId, String articleId, String title, String content, String type, String userId, String createIp, String contextPath) {
	
		messageId = messageId != null ? messageId : SystemUtil.getUUIDString();
		articleId = articleId != null ? articleId : SystemUtil.getUUIDString();
		ArticleDetailMsgDto articleMsg = new ArticleDetailMsgDto(messageId, articleId, SystemUtil.getUUIDString());
		articleMsg.setArticleTypeMsg(ArticleTypeMsg.getArticleType(type));
		articleMsg.setMsgContent(SystemUtil.removeAllScriptFromHtml(content));
		articleMsg.setMsgCreateDttm(DateUtil.convertCurrentDTTMtoInt());
		articleMsg.setMsgCreateIp(createIp);
		ArticleAuthor author = new ArticleAuthor(userId, "");
		articleMsg.setAuthor(author);
		articleMsg.setMsgTitle(title);
		
		return articleMsg;
	}
	
	/**
	 * @功能 添加回复内容
	 * @author ZCW
	 * */
	@RequestMapping("/addArticleMessage")
	@ResponseBody
	public Map<String, Object> addArticleMessage(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (request.getSession().getAttribute(SystemConstants.LOGINUSER_SESSION_NAME) != null) {
			String articleContent = SystemUtil.removeAllScriptFromHtml(assertNotEmpty(request.getParameter("content")));
			String articleType = assertNotEmpty(request.getParameter("article_type"));
			String parentMessageId = assertNotEmpty(request.getParameter("pId"));// 需要父节点的ID
			UserInfoDto user = (UserInfoDto) request.getSession().getAttribute(SystemConstants.LOGINUSER_SESSION_NAME);
			String userId = user.getUserId();
			String articleCreateIp = assertNotEmpty(SystemUtil.getRequestIp(request));
			String contextPath = request.getContextPath();
			ArticleDetailMsgDto articleMsg = getArticleInfoMsg(parentMessageId, null, "", articleContent, articleType, userId, articleCreateIp, contextPath);
			
			long messageId = playArticleService.doAddArticleMessage(articleMsg);
			
			resultMap.put("result", SystemConstants.AJAX_SUCCESS);
			resultMap.put("mi", SystemUtil.encrypt(String.valueOf(messageId))); //将messageId返回去
			ArticleAuthor author = new ArticleAuthor(userId, user.getPositionId());
			author.setAuthorName(user.getNickName());
			author.setSex(user.getUserSex());
			author.setUserLogoUrl(user.getUserLogoUrl());
			resultMap.put("author", author);
		} else {
			resultMap.put("result", SystemConstants.AJAX_FAILED_ALERT);
			resultMap.put("message", "请先登录");
		}
		
		return resultMap;
	}
	
	/**
	 * @功能 删除文章
	 * @author LH
	 * */
	@RequestMapping(value="/ajaxDeleteArticle")
	@ResponseBody
	public boolean ajaxDeleteArticle(HttpServletRequest request, HttpServletResponse response) {
		String articleId = assertNotEmpty(request.getParameter("articleId"));
		
		playArticleService.doDeleteArticle(articleId);
		
		return true;
	} 
	
	
	/**
	 * @功能 设置文章的内容
	 * @author LH
	 * @return ArticleInfoDto 设置过后的文章内容
	 */
	private ArticleInfoDto createArticleInfoDto(String articleId, String articleTitle, 
			String articleSummaryText, String artSummaryPicUrl, int articleCreateDttm, 
			String articleCreateIp, String articleType, String userId){
		String positionId = "";
		ArticleInfoDto articleInfo = new ArticleInfoDto(articleId);
		ArticleAuthor author = new ArticleAuthor(userId, positionId);
		
		articleInfo.setArticleTitle(articleTitle);
		articleInfo.setArticleSummaryText(articleSummaryText);
		articleInfo.setArtSummaryPicUrl(artSummaryPicUrl);
		articleInfo.setArticleCreateDttm(articleCreateDttm);
		articleInfo.setArticleCreateIp(articleCreateIp);
		articleInfo.setArticleCreateDttm(articleCreateDttm);
		articleInfo.setArticleType(ArticleType.getArticleType(articleType));
		articleInfo.setAuthor(author);
		
		return articleInfo;
	}
}
